﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.DayStatistics
{
    public partial class Day5MinsStatistics : Page
    {
        private SearchStatisticsViewModel m_ViewModel;

        public Day5MinsStatistics()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Day5MinsStatistics_Loaded);
        }

        #region Event Methods

        private void Day5MinsStatistics_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            this.startDatePicker.SelectedDate = DateTime.Now;

            m_ViewModel = new SearchStatisticsViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                string title1 = title;
                Axis xAxis = new Axis();
                DateTime minDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Min();
                DateTime maxDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Max();
                xAxis.AxisMinimum = minDateTime;
                xAxis.AxisMaximum = maxDateTime;
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1.5;
                vcChart1.AxesX.Add(xAxis);

                int max = 0;
                double avg = 0;
                string path = cmbInorOut.SelectedIndex == 0 ? "InCount" : "OutCount";
                string seriesTitle = "进";
                if (cmbInorOut.SelectedIndex == 0)
                {
                    seriesTitle = "进";
                    title1 = string.Format(title, "进客流");
                    max = firstHistoryPassengerFlow.Select(s => s.InCount).Max();
                    avg = firstHistoryPassengerFlow.Select(s => s.InCount).Average();
                }
                else
                {
                    seriesTitle = "出";
                    title1 = string.Format(title, "出客流");
                    max = firstHistoryPassengerFlow.Select(s => s.OutCount).Max();
                    avg = firstHistoryPassengerFlow.Select(s => s.OutCount).Average();
                }

                Title vcChart1Title = new Visifire.Charts.Title();
                vcChart1Title.Text = title1;
                vcChart1.Titles.Add(vcChart1Title);

                TrendLine maxLine = new TrendLine();
                maxLine.Value = max;
                maxLine.LabelText = "最大:" + max.ToString();
                maxLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
                maxLine.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

                TrendLine avgLine = new TrendLine();
                avgLine.Value = avg;
                avgLine.LabelText = "平均:" + Convert.ToInt32(avg).ToString();
                avgLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
                vcChart1.TrendLines.Add(maxLine);
                vcChart1.TrendLines.Add(avgLine);

                DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, seriesTitle, ChartValueTypes.DateTime);
                series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", path));
                series.DataSource = firstHistoryPassengerFlow;
                vcChart1.Series.Add(series);

                string title2 = string.Format(title, "滞留人数");
                Title vcChart2Title = new Visifire.Charts.Title();
                vcChart2Title.Text = title2;
                vcChart2.Titles.Add(vcChart2Title);
                vcChart2.AxesX.Add(xAxis);

                DataSeries strandedSeries = ChartHelper.GetDataSeries(RenderAs.Line, "滞留人数", ChartValueTypes.DateTime);
                strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "StrandedCount"));
                strandedSeries.DataSource = firstHistoryPassengerFlow;
                vcChart2.Series.Add(strandedSeries);

                this.dataGrid.ItemsSource = firstHistoryPassengerFlow;

            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                }

                if (vcChart2 != null)
                {
                    vcChart2.AxesX.Clear();
                    vcChart2.TrendLines.Clear();
                    vcChart2.Series.Clear();
                    vcChart2.Titles.Clear();
                }
            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                    if (selectedArea.Count > 1)
                    {
                        this.cmbPassenger.IsEnabled = false;
                    }
                    else
                    {
                        this.cmbPassenger.IsEnabled = true;
                    }

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
                cmbPassenger_DropDownClosed(null, null);
            }
        }

        private void cmbPassenger_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                var selectMonitorAreaExts = m_ViewModel.MonitorAreaGateExts.Where(a => a.IsSelected).ToList();

                if (selectMonitorAreaExts.Count > 0)
                {
                    cbItemDisplay2.Content = selectMonitorAreaExts.Count > 1 ? selectMonitorAreaExts[0].Name + "..." : selectMonitorAreaExts[0].Name;

                }
                else
                {
                    cbItemDisplay2.Content = string.Empty;
                }
                cmbPassenger.SelectedItem = null;
                cmbPassenger.SelectedItem = cbItemDisplay2;
            }
        }
        
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime startTime = new DateTime(startDatePicker.SelectedDate.Value.Year,
                                                  startDatePicker.SelectedDate.Value.Month,
                                                  startDatePicker.SelectedDate.Value.Day,
                                                  0, 0, 0);
                DateTime endTime = startTime.AddDays(1);

                if (endTime < startTime)
                {
                    MessageBox.Show("开始时间不能大于结束时间");
                }
                else
                {
                    bool isIn = cmbInorOut.SelectedIndex == 0 ? true : false;
                    m_ViewModel.RefreshDay5MinsPassengerFlows(startTime, endTime);
                }
            }
        }

        #endregion

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
